package co.edu.unal.cg.splines.interact;

import java.util.ArrayList;

import processing.core.PApplet;
import processing.core.PVector;
import remixlab.proscene.InteractiveFrame;
import remixlab.proscene.Scene;
import co.edu.unal.cg.splines.NaturalSpline;

public class InteractiveNaturalSpline implements InteractiveSpline {

	ArrayList<NaturalSplineControlPoint> controlPoints = new ArrayList<NaturalSplineControlPoint>();
	Scene scene;
	NaturalSpline spline;

	public InteractiveNaturalSpline(Scene scene) {
		this.scene = scene;
		this.spline = new NaturalSpline(0.1);
	}

	public void addControlPoint(PVector point) {
		NaturalSplineControlPoint control = new NaturalSplineControlPoint(
				point, scene, spline);
		controlPoints.add(control);
	}

	public void draw(PApplet canvas) {
		for (NaturalSplineControlPoint controlPoint : controlPoints) {
			controlPoint.draw(canvas);
		}
		this.spline.draw(canvas);
	}

	public class NaturalSplineControlPoint {

		private final float r = 1;

		InteractiveFrame frame;
		PVector controlPointReference;

		public NaturalSplineControlPoint(PVector position, Scene scene,
				NaturalSpline spline) {
			this.frame = new InteractiveFrame(scene);
			this.frame.setPosition(position);
			controlPointReference = position;
			spline.addControlPoint(controlPointReference);
		}

		public void draw(PApplet canvas) {
			canvas.pushMatrix();
			canvas.pushStyle();
			this.drawShape(canvas);
			updateReferenceControlPoint();
			canvas.popStyle();
			canvas.popMatrix();
		}

		private void updateReferenceControlPoint() {
			PVector pos = this.frame.position();
			this.controlPointReference.x = pos.x;
			this.controlPointReference.y = pos.y;
			this.controlPointReference.z = pos.z;
		}

		private void drawShape(PApplet canvas) {
			// Multiply matrix to get in the frame coordinate system.
			// scene.parent.applyMatrix(iFrame.matrix()) is handy but
			// inefficient
			frame.applyTransformation(); // optimum
			canvas.noStroke();
			if (frame.grabsMouse())
				canvas.fill(255, 0, 0);
			else
				canvas.fill(this.getColor());
			// Draw a box
			canvas.sphere(r);
		}

		private int getColor() {
			return 100;
		}

	}
}
